package initialize

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"week1zk-project/user-rpc/global"
)

//初始化nacos

func InitNacos() {
	nacos := &global.AppData.Nacos
	clientConfig := constant.ClientConfig{
		NamespaceId:         nacos.NameSpace, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      nacos.Host,
			ContextPath: "/nacos",
			Port:        uint64(nacos.Port),
			Scheme:      "http",
		},
	}
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(errors.New("nacos连接失败"))
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: nacos.DataId,
		Group:  nacos.Group})
	if err != nil {
		panic(errors.New("nacos配置读取失败"))
	}
	json.Unmarshal([]byte(content), &global.AppData.Service)
	fmt.Println("nacos配置读取成功", &global.AppData.Service)

}
